<template>
	<view class="login_container">
		<view :style="{ height: navigationBarHeight + 'rpx' }">
		</view>
		<view class="navigation" :style="{ height: statusBarHeight + 'rpx' }">
			<text>登录</text>
		</view>
		<view class="user_avatar_wrapper">
			<view class="user_avatar">
				<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="handleAvatar">登录</button>
				<image :src="avatarUrl || '../static/images/default_avatar.png'" mode="aspectFill" class="avatar"
					:style="{ width: avatarUrl ? '100%' : '180rpx', height: avatarUrl ? '100%' : '180rpx' }">
				</image>
			</view>
		</view>
		<view class="form_wrapper">
			<rForm ref="formRef" v-model="formData" :rules="rules">
				<rFormItem label="姓名" prop="nickName">
					<input type="text" class="_form_item_input" v-model="formData.nickName" placeholder="请输入姓名" />
				</rFormItem>
				<rFormItem label="联系方式" prop="phone">
					<input type="digit" class="_form_item_input" v-model="formData.phone" placeholder="请输入联系方式" />
				</rFormItem>
				<rFormItem label="身份证号码" prop="idCard">
					<input type="text" @blur="handleUserAvatar" class="_form_item_input" v-model="formData.idCard"
						placeholder="请输入身份证号码" />
				</rFormItem>
				<rFormItem label="工作单位" prop="unit">
					<input type="text" class="_form_item_input" v-model="formData.unit" placeholder="请输入工作单位" />
				</rFormItem>
			</rForm>
		</view>
		<view class="agreement_wrapper">
			<view class="agreement_content">
				<up-checkbox-group v-model="checked" placement="row">
					<up-checkbox shape="circle" activeColor="#fa6146"></up-checkbox>
				</up-checkbox-group>
				<text @click="handleAgreementClick">我已阅读并同意 <text class="agreement_link">《用户协议》</text></text>
			</view>
		</view>
		<view class="_submit_btn" @click="handleLogin">立即登录</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import rForm from '@/components/r-from.vue'
	import rFormItem from '@/components/r-form-item.vue'
	import {
		userLogin,
		getUserAvatar,
		autoLogin
	} from '../api/user';
	import {
		uploadFile
	} from '../api/common.js'
	import {
		targetUrl
	} from '../uitls/request';
	import {
		ASSETS_URL
	} from '../uitls/global.js'
	const formRef = ref(null);
	const navigationBarHeight = getApp().globalData.navigationBarHeight
	const statusBarHeight = getApp().globalData.statusBarHeight
	const avatarUrl = ref('')
	const rules = {
		nickName: {
			type: 'name',
			msg: '请输入有效姓名'
		},
		phone: {
			type: 'phone',
			msg: '请输入有效电话'
		},
		idCard: {
			type: 'idCard',
			msg: '请输入有效身份证'
		},
		unit: {
			type: 'text',
			msg: '请输入有效工作地点'
		}
	}
	let changeAvatarStatus = false;

	let formData = reactive({
		avatarUrl: '',
		nickName: '',
		phone: '',
		idCard: '',
		unit: ''
	})

	//头像更换之后就上传
	const handleAvatar = (e) => {
		changeAvatarStatus = true;
		avatarUrl.value = e.detail.avatarUrl
		//上传头像
		uploadFile(avatarUrl.value, async (res) => {
			const url = JSON.parse(res.data).data;
			formData.avatarUrl = url;
		}, () => {
			wx.showToast({
				title: "头像上传失败，请稍后重试",
				icon: 'none'
			})
		});
	}

	let checked = ref([]);

	function handleLogin() {
		if (checked.value.length === 0) {
			uni.showToast({
				title: '请先同意用户协议',
				icon: 'none'
			})
			return
		}
		const valid = formRef.value.validate()
		console.log(valid);

		if (valid) {
			// 验证通过，可以提交表单
			preLogin();
		} else {
			// 验证失败
		}
	}
	async function preLogin() {
		if (formData.avatarUrl === '') {
			wx.showToast({
				title: "请选择一个头像",
				icon: "none"
			})
			return;
		}
		//获取openid
		const {
			code: code
		} = await wx.login();
		const {
			data
		} = await userLogin(formData, code)
		//判断是否登录成功
		if (data) {
			uni.setStorageSync("openId", data.openId);
			uni.setStorageSync("userId", data.userId);
			uni.switchTab({
				url: "/pages/index/index"
			})
		}
	}

	//获取用户头像
	async function handleUserAvatar() {
		if (changeAvatarStatus) return;
		const {
			data
		} = await getUserAvatar(formData.idCard)
		console.log(data);
		if (data) {
			formData.avatarUrl = data;
			avatarUrl.value = targetUrl + 'uploadFile/' + data;
		}
	}
	//点击用户协议
	function handleAgreementClick() {
		uni.navigateTo({
			url: "/pages/agreement"
		})
	}


	onMounted(async () => {
		// 自动登录
		const {
			code: code
		} = await wx.login();
		if (code) {
			//查询是否是 老用户/已经登陆过
			const {
				data
			} = await autoLogin(code)
			if (data) {
				// formData = data;
				Object.keys(formData).forEach(el => {
					formData[el] = data[el]
				})
				avatarUrl.value = ASSETS_URL + formData.avatarUrl;
				uni.setStorageSync("openId", data.openId);
				uni.setStorageSync("userId", data.userId);
				uni.showToast({
					title: '登陆中...',
					icon: 'none'
				})
				setTimeout(() => {
					uni.switchTab({
						url: "/pages/index/index"
					})
				}, 1000)

			}
		}
	})
</script>

<style lang="scss">
	.login_container {
		width: 100%;
		height: 100%;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx 50rpx;
		box-sizing: border-box;
		gap: 50rpx;
	}

	.user_avatar_wrapper {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.user_avatar {
		position: relative;
		width: 250rpx;
		height: 250rpx;
		border-radius: 50%;
		overflow: hidden;
		background-color: #e5e5e5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.avatar-btn {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			opacity: 0;
			z-index: 1;
		}
	}

	.form_wrapper {
		width: 100%;
		box-sizing: border-box;
	}

	.agreement_wrapper {
		width: 100%;
		background-color: #f6f6f6;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.agreement_link {
		color: $r-main-color;
	}

	.agreement_content {
		width: 100%;
		display: flex;
		gap: 10rpx;
		height: 20rpx;
		align-items: center;
	}
</style>